package com.sf.osms.dep.processor.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class StringUtil {
	private static Logger logger = Logger.getLogger(StringUtil.class);
	private static String assistDelimiter = "%";
	
	public static String getCaptialLineStr(File file,String lineSepartor,String encoding){
		
		if(StringUtils.isEmpty(lineSepartor)){
			lineSepartor = ""; //回车键
		}
		if(StringUtils.isBlank(encoding)){
			encoding = "UTF-8";
		}
		//不是换行符为分割符
		if(!"".equalsIgnoreCase(lineSepartor)){
			LineSplitBufferedReader br = null;
			try {
				br = new LineSplitBufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
				br.setLineSplit(lineSepartor);
				return br.readLine();
			}catch(Exception e){
				
				logger.error(ExceptionUtils.getExceptionStackString(e));
			}finally{
				if(br != null){
					try {
						br.close();
					} catch (IOException e) {
						logger.error(ExceptionUtils.getExceptionStackString(e));
					}
				}
			}
		}else{
			BufferedReader br = null;
			InputStream in = null;
			try {
				in = new FileInputStream(file);
				br = new BufferedReader(new InputStreamReader(in,encoding));
				return br.readLine();
			}catch(Exception e){
				logger.error(ExceptionUtils.getExceptionStackString(e));
			}finally{
				if(br != null){
					try {
						br.close();
					} catch (IOException e) {
						logger.error(ExceptionUtils.getExceptionStackString(e));
				}
				}
			}
		}
		return null;
	}
	
	public static String codeString(File file)
			throws Exception {

		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
				file));
		int p = (bin.read() << 8) + bin.read();
		String code = "UTF-8";

		switch (p) {
		case 29537:
		case 0xefbb:
			code = "UTF-8";
			break;
		case 0xfffe:
			code = "Unicode";
			break;
		case 0xfeff:
			code = "UTF-16BE";
			break;
		case 20338:
		case 8846:
			code = "Shift-JIS";
			break;
		default:
			code = "UTF-8";
		}
		if (bin != null) {
			bin.close();
		}
		return code;

	}
	
	public static String[] getStringValues(String lineStr, String separator){

		String[] values =  lineStr.replaceAll(separator, assistDelimiter + separator + assistDelimiter).split(separator);
		String[] results = new String[values.length];
		if(values != null){
			for(int i=0;i<values.length;i++){
				String str = values[i].replaceAll(assistDelimiter, "");
				results[i] = str;
			}
		}
		return results;
	}
	
	 /**
	  * 解析数据中的双引号
	 */
	public static String[] removeDoubleQuotes(String[] values){
		if(values == null || values.length == 0){
			return values;
		}
		String[] newValues = new String[values.length];
		for(int i=0;i<values.length;i++){
			newValues[i] = values[i].replaceAll("\"", " ").trim();
		}
		return newValues;
	}
	
	public static String escapeRegexSpecialWord(String keyword) {  
	    if (StringUtils.isNotBlank(keyword)) {  
	        String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };  
	        for (String key : fbsArr) {  
	            if (keyword.contains(key)) {  
	                keyword = keyword.replace(key, "\\" + key);  
	            }  
	        }  
	    }  
	    return keyword;  
	}  
	
	public static String[] splitCSV(String lineStr,String columnSplit){
		if(RouterConstants.AGENT_FILE_SPLIT_NUM.equals(columnSplit)){
			return new String[]{lineStr};
		}
		if(lineStr.startsWith(columnSplit)){
			lineStr = "\"\"" + lineStr;
		}
		columnSplit = escapeRegexSpecialWord(columnSplit);
		String regex = "\\G(?:^|" + columnSplit + ")(?:\"([^\"]*+(?:\"\"[^\"]*+)*+)\"|([^\"" + columnSplit + "]*+))";  
		Matcher main = Pattern.compile(regex,Pattern.COMMENTS).matcher("");  
	    Matcher mquote = Pattern.compile("\"\"").matcher("");
	    List<String> list = new ArrayList<String>();
	    main.reset(lineStr);
        while (main.find()) {  
            String field = "";  
            if (main.start(2) >= 0) {  
                field = main.group(2);  
            } else {  
                field = mquote.reset(main.group(1)).replaceAll("\"");  
            }  
            list.add(field);
        }  
        String[] columns = new String[list.size()];
        for(int i=0;i<columns.length;i++){
        	columns[i] = list.get(i);
        }
		return columns;
	}
	
	
	public static void main(String[] args) {
		String lineStr = "2$1$\"081000158937\"$$\"CUI SHANG $ZHI ZI›HH\"$\"TOKYO TO MEGURO KU HIGASHIYAMA 1-2-2\"$\"0357252478\"$";
		
		String[] splitCSV = splitCSV(lineStr, "$");
		for (String string : splitCSV) {
			System.out.println(string);
		}
		
		System.out.println(connectStr(",", "22",""));
		System.out.println(repairStrLen("111", '0',4));
	}
	
	// 过滤特殊字符
	public static String StringFilter(String str, String regEx) {
		if (null == str) {
			return null;
		}
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
	
	public static String connectStr(String delimiter,String...strs){
		if(null == delimiter || null == strs || strs.length == 0){
			return null;
		}
		StringBuffer sb = new StringBuffer();
		for (String str : strs) {			
			if(!StringUtils.isBlank(str)){
				sb.append(delimiter);
				sb.append(str.trim());
			}
		}
		String newStr = sb.toString();
		return newStr.substring(newStr.indexOf(delimiter)+1);
	}
	
	/**
	 * 将字符串进行默认长度的补充
	 * @param str 源字符串
	 * @param repairChar 需要补充的字符
	 * @param len 字符串的最小长度
	 * @return
	 */
	public static String repairStrLen(String str,char repairChar,int len){
		
		if(str.length() < len){
			int c = len - str.length();
			for(int i=0;i<c;i++){
				str = repairChar + str;
			}
		}
		return str;
	}

}
